//
//  MoveHouseViewController.m
//  MoveHouse
//
//  Created by 张垚 on 16/6/6.
//  Copyright © 2016年 众杰网络. All rights reserved.
//

#import "MoveHouseViewController.h"
#import "MoveHousePushTableViewCell.h"
#import "ReuseRandomCodeTableViewCell.h"
#import "MoveHouseAreaChooseViewController.h"
#import "LabelAndTextFieldView.h"
#import "BaseTitleNavigationBar.h"
#import "SubmitMenuManager.h"




@interface MoveHouseViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>
/* tableView属性 */
@property (nonatomic, strong) UITableView *tableView;
/* 描述标题 */
@property (nonatomic, strong) NSArray *infoArr;
/* 占位数据 */
@property (nonatomic, strong) NSArray *contentArr;
/* 提交 */
@property (nonatomic, strong) UIButton *submitButton;
/* 联系客服 */
@property (nonatomic, strong) UIButton *contactCustomerServiceButton;
/* 键盘高度 */
@property (nonatomic, assign) CGFloat kbHeight;
/* 顶部自定义导航栏 */
@property (nonatomic, strong) BaseTitleNavigationBar *myBar;
/* 装key的数组 */
@property (nonatomic, strong) NSArray *keyArr;

@property (nonatomic, strong) MBProgressHUD *hud;
@end



@implementation MoveHouseViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}


#pragma mark - 主程序入口
- (void)viewDidLoad {
    [super viewDidLoad];
     self.automaticallyAdjustsScrollViewInsets = NO;
    /* 设置默认键盘高度 */
    _kbHeight = 258.0f;
    /* 注册键盘监听通知 */
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    self.view.backgroundColor = [UIColor colorWithRed:0.902 green:0.902 blue:0.902 alpha:1.0];
    /* 数据 */
    _infoArr = @[@"服务区域", @"联系人", @"服务项目", @"详细地址", @"面积大小", @"手机号", @"验证码"];
   _contentArr = @[@"请选择位置", @"请输入姓名或者称呼", @"请选择服务项目",@"请输入地址(至少6字以上)", @"请选择要保洁房间的平米数", @"请输入11位手机号", @"请输入验证码"];
    _keyArr = @[@"userid", @"areaid", @"truename", @"catid", @"address", @"hits", @"telephone"];
    /* tableview */
    [self initTableView];
    /* 提交按钮 */
    [self creatSubmitButton];
    [self initNavigationBar];
    // Do any additional setup after loading the view.
}
#pragma mark - 顶部视图创建 返回点击
//顶部视图
- (void)initNavigationBar {
    _myBar = [[BaseTitleNavigationBar alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 64) WithTitleStr:@"保洁"];
    [self.view addSubview:_myBar];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(back)];
    [_myBar.leftView addGestureRecognizer:tap];
}
//返回上一界面
- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - 键盘监听事件
- (void)keyboardWillShow:(NSNotification *)showNotification {
    /*获取键盘高度 中英文下高度是不同的 */
    CGFloat kbHeight = [[showNotification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    /* 将高度赋给属性 第一次默认是258 如果有改动的话 根据监听进行改动 */
    _kbHeight = kbHeight;
    
}
- (void)keyboardWillHide:(NSNotification *)hideNotification {
    // 取得键盘的动画时间，这样可以在视图上移的时候更连贯
    double duration = [[hideNotification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        _tableView.frame = CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64);
    }];
}

#pragma mark - 提交 联系客服
/* 提交按钮 联系客服 */
- (void)creatSubmitButton {
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 80)];
    _submitButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _submitButton.backgroundColor = [UIColor colorWithRed:212 / 255.0f green:38 / 255.0f blue:26 / 255.0f alpha:1.0];
    _submitButton.layer.masksToBounds = YES;
    _submitButton.layer.cornerRadius = 6;
    [footerView addSubview:_submitButton];
    [_submitButton setTitle:@"提交" forState:UIControlStateNormal];
    [_submitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _submitButton.titleLabel.font = [UIFont systemFontOfSize:18 weight:18];
    [_submitButton addTarget:self action:@selector(submit:) forControlEvents:UIControlEventTouchUpInside];
    
    _contactCustomerServiceButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _contactCustomerServiceButton.backgroundColor = [UIColor colorWithRed:212 / 255.0f green:38 / 255.0f blue:26 / 255.0f alpha:1.0];
    _contactCustomerServiceButton.layer.masksToBounds = YES;
    _contactCustomerServiceButton.layer.cornerRadius = 6;
    [_contactCustomerServiceButton setTitle:@"联系客服" forState:UIControlStateNormal];
    [_contactCustomerServiceButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _contactCustomerServiceButton.titleLabel.font = [UIFont systemFontOfSize:18 weight:18];
    [footerView addSubview:_contactCustomerServiceButton];
    [_contactCustomerServiceButton addTarget:self action:@selector(contactPerson:) forControlEvents:UIControlEventTouchUpInside];
    
    
    [_submitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(footerView.mas_top).offset(25);
        make.left.equalTo(footerView.mas_left).offset(50);
        make.right.equalTo(_contactCustomerServiceButton.mas_left).offset(-40);
        make.width.equalTo(_contactCustomerServiceButton.mas_width);
    }];
    [_contactCustomerServiceButton mas_makeConstraints:^(MASConstraintMaker *make) {
         make.top.equalTo(footerView.mas_top).offset(25);
        make.right.equalTo(footerView.mas_right).offset(-50);
        make.width.equalTo(_submitButton.mas_width);
        
    }];
    _tableView.tableFooterView = footerView;
    
}

/* 提交资料 预留接口 */
- (void)submit:(UIButton *)button {
   NSDictionary *dic = [SubmitMenuManager submitCleanHouseTableView:_tableView WithKeyArr:_keyArr];
    NSString *street = dic[@"address"];
    if ([dic[@"areaid"] isEqualToString:@"0"]) {
        [self alertMessage:@"请选择区域"];
    }else if ([dic[@"truename"] isEqualToString:@""]) {
        [self alertMessage:@"请输入姓名"];
    }else if ([dic[@"catid"] isEqualToString:@"0"]) {
        [self alertMessage:@"请选择服务项目"];
    }else if (street.length <= 6) {
        [self alertMessage:@"详细地址不得少于6个字"];
    }else if ([dic[@"hits"] isEqualToString:@""]) {
        [self alertMessage:@"请输入房屋面积"];
    }else {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:6 inSection:0];
        ReuseRandomCodeTableViewCell *cell = [_tableView cellForRowAtIndexPath:indexPath];
        if ([cell.inputView.contextTextField.text isEqualToString:[[NSUserDefaults standardUserDefaults] objectForKey:@"PHPCode"] ]) {
            if ([dic[@"telephone"] isEqualToString:[[NSUserDefaults standardUserDefaults] objectForKey:@"codeTelNumber"]]) {
                _hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                _hud.label.text = @"上传中";
                _hud.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor;
                _hud.animationType = MBProgressHUDAnimationZoomIn;
                [NetRequest updateOrGetInformationFromUrl:@"http://aizufang.hrbzjwl.com/tp/api.php/Index/App_baojie" withParameters:dic success:^(NSURLSessionDataTask *task, id responseObject) {
                    if ([[responseObject[@"flg"] description] isEqualToString:@"1"]) {
                        _hud.label.text = @"上传成功";
                        [_hud hideAnimated:YES afterDelay:1];
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [self back];
                        });
                    }else {
                        _hud.label.text = @"上传失败";
                        [_hud hideAnimated:YES afterDelay:1];
                    }
                } failure:^(NSURLSessionDataTask *task, NSError *error) {
                    _hud.label.text = @"服务器异常，请重试";
                    [_hud hideAnimated:YES afterDelay:1];
                }];
            }else {
                [self alertMessage:@"手机号不匹配"];
            }
        }else {
            [self alertMessage:@"验证码输入有误"];
        }
    }
 
}
/* 联系客服 拨打电话 */
- (void)contactPerson:(UIButton *)button {
    NSMutableString *str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",unifyServiceNumber];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}

#pragma mark - tableView 

/* 创建tableView */
- (void)initTableView {
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [self.view addSubview:_tableView];
    [_tableView registerClass:[MoveHousePushTableViewCell class] forCellReuseIdentifier:NSStringFromClass([MoveHousePushTableViewCell class])];
    [_tableView registerClass:[ReuseRandomCodeTableViewCell class] forCellReuseIdentifier:NSStringFromClass([ReuseRandomCodeTableViewCell class])];
}
/* 行数 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _infoArr.count;
}
/* cell创建 */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 6) {
        ReuseRandomCodeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ReuseRandomCodeTableViewCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.inputView.titleLabel.text = _infoArr[indexPath.row];
        cell.inputView.contextTextField.placeholder = _contentArr[indexPath.row];
        cell.inputView.contextTextField.tag = indexPath.row + 1;
        cell.inputView.contextTextField.delegate = self;
        [cell.getRandomCodeButton addTarget:self action:@selector(getRandomCode:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }else {
        MoveHousePushTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MoveHousePushTableViewCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (indexPath.row == 0 || indexPath.row == 2) {
            cell.inputView.userInteractionEnabled = NO;
            cell.isPush = YES;
        }else {
            cell.isPush = NO;
        }
        if (indexPath.row == 3) {
            NSRange range = {5, 8};
            NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:_contentArr[indexPath.row]];
            [str addAttribute:NSForegroundColorAttributeName value:KNaviBackColor range:range];
            cell.inputView.contextTextField.attributedPlaceholder = str;
        }
        cell.inputView.titleLabel.text = _infoArr[indexPath.row];
        cell.inputView.contextTextField.placeholder = _contentArr[indexPath.row];
        cell.inputView.contextTextField.delegate = self;
        return cell;
    }
    }
/* 点击cell 区域选择的就跳转 否则没有响应 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0 || indexPath.row == 2) {
        MoveHousePushTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        MoveHouseAreaChooseViewController *areaChooseVC = [[MoveHouseAreaChooseViewController alloc] init];
        if (indexPath.row == 0) {
            areaChooseVC.categoryStr = @"区域选择";
            areaChooseVC.currentStr = cell.inputView.contextTextField.text;
            [areaChooseVC passInfoToPreviousPage:^(NSString *infoStr, NSInteger tag) {
                cell.inputView.contextTextField.text = infoStr;
                cell.tag = tag;
            }];
        }else if (indexPath.row == 2) {
            areaChooseVC.categoryStr = @"服务项目";
            areaChooseVC.currentStr = cell.inputView.contextTextField.text;
            [areaChooseVC passInfoToPreviousPage:^(NSString *infoStr, NSInteger tag) {
                cell.inputView.contextTextField.text = infoStr;
                cell.tag = tag;
            }];
        }
        [self.navigationController pushViewController:areaChooseVC animated:YES];
    }
}
#pragma mark - 获取验证码
//获取验证码
- (void)getRandomCode:(UIButton *)button {
    //获取手机号所在的cell
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:5 inSection:0];
    MoveHousePushTableViewCell *cell = [_tableView cellForRowAtIndexPath:indexPath];
    if ([self valiMobile:cell.inputView.contextTextField.text] == nil) {
        [[NSUserDefaults standardUserDefaults] setObject:cell.inputView.contextTextField.text forKey:@"codeTelNumber"];
        button.enabled = NO;
        [button setTitle:@"60s后重新获取" forState:UIControlStateNormal];
        NSDate *oldDate = [[NSDate alloc]initWithTimeIntervalSinceNow:0];
        NSUserDefaults *userDefaults = [[NSUserDefaults alloc]init];
        [userDefaults setObject:oldDate forKey:@"verficationOldTime"];
        [userDefaults synchronize];
        [self performSelector:@selector(updateVerificationButton) withObject:nil afterDelay:1.0];
        [NetRequest getCodeNumberWithPhoneNumber:cell.inputView.contextTextField.text success:^(NSURLSessionDataTask *task, id responseObject) {
            [[NSUserDefaults standardUserDefaults] setObject:responseObject forKey:@"PHPCode"];
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
        }];
    }else {
        [self alertMessage:[self valiMobile:cell.inputView.contextTextField.text]];
    }
}
//实时刷新button上面的文字
- (void)updateVerificationButton{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:6 inSection:0];
    ReuseRandomCodeTableViewCell *cell = [_tableView cellForRowAtIndexPath:indexPath];
    NSDate *nowDate = [[NSDate alloc]initWithTimeIntervalSinceNow:0];
    NSUserDefaults *userDefaults = [[NSUserDefaults alloc]init];
    NSDate *oldDate = [userDefaults objectForKey:@"verficationOldTime"];
    NSInteger distance = 60 - [nowDate timeIntervalSinceDate:oldDate];
    if (distance>0) {
        [cell.getRandomCodeButton setTitle:[NSString stringWithFormat:@"%lds重新获取",(long)distance] forState:UIControlStateNormal];
        [self performSelector:@selector(updateVerificationButton) withObject:nil afterDelay:1.0];
    }else{
        [cell.getRandomCodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        cell.getRandomCodeButton.enabled = YES;
    }
}
//提示信息
- (void)alertMessage:(NSString *)alertMessage {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:alertMessage preferredStyle:UIAlertControllerStyleAlert];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self dismissViewControllerAnimated:YES completion:nil];
    });
    [self presentViewController:alertController animated:YES completion:nil];
    
}
//手机号验证
- (NSString *)valiMobile:(NSString *)mobile{
    if (mobile.length < 11)
    {
        return @"请输入11位手机号";
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return nil;
        }else{
            return @"请输入正确格式的手机号";
        }
    }
    return nil;
}

#pragma mark - 代理协议方法
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    /* 释放第一响应 */
    [textField resignFirstResponder];
    return YES;
}
/* 开始编辑的时候 键盘弹起 视图上移 */
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    UIView *view = textField.superview;
    while (![view isKindOfClass:[UITableViewCell class]]) {
        view = [view superview];
    }
    UITableViewCell *cell = (UITableViewCell*)view;
    CGRect rect = [cell convertRect:cell.frame toView:self.view];
    if (rect.origin.y / 2 + rect.size.height >= self.view.frame.size.height - _kbHeight) {
        CGFloat offset = _kbHeight;
        [UIView animateWithDuration:0.25 animations:^{
            _tableView.frame = CGRectMake(0, -offset + 64, self.view.frame.size.width, self.view.frame.size.height);
        }];
    }
    return YES;
}

#pragma mark - 移除观察者 
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
